const connections = require('../app/database')
class AddressService {
  async addAddressService(address) {
    const { name, tel, province, city, county, addressDetail, areaCode, postalCode, isDefault_int, userId } = address
    const statement = 'INSERT INTO `user-address`(name, tel, province, city, county, addressDetail, areaCode, postalCode, isDefault_int, userId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
    try {
      const res = await connections.execute(statement, [name, tel, province, city, county, addressDetail, areaCode, postalCode, isDefault_int, userId])
      return res[0]
    } catch (error) {
      console.log(error)
    }
  }
  async getAllAddressService(userId) {
    console.log(222);
    const statement = 'SELECT * FROM `user-address` WHERE userId = ?'
    try {
      const res = await connections.execute(statement, [userId])
      return res[0]
    } catch (error) {
      console.log(error);
    }
  }
  async updateDefaultService(userId) {
    try {
      await connections.execute('UPDATE `user-address` SET isDefault_int = 0 WHERE userId = ?', [userId])
      return true
    } catch (error) {
      console.log(error);
    }
  }
  async deleteAddressService(id) {
    try {
      const res = await connections.execute('DELETE FROM `user-address` WHERE id = ?', [id])
      return res[0]
    } catch (error) {
      console.log(error);
    }
  }
  async getAddressService(id) {
    try {
      const res = await connections.execute('SELECT * FROM `user-address` WHERE id = ?',
        [id])
      return res[0]
    } catch (error) {
      console.log(error);
    }
  }
  async updateAddressService(address) {
    console.log(address);
    const { name, tel, province, city, county, addressDetail, areaCode, postalCode, isDefault_int, userId, id } = address
    try {
      const res = await connections.execute('UPDATE `user-address` SET name = ?, tel = ?, province = ?, city = ?, county =?, addressDetail = ?, areaCode = ?, postalCode = ?, isDefault_int = ?, userId = ? WHERE id = ? ', [
        name, tel, province, city, county, addressDetail, areaCode, postalCode, isDefault_int, userId, id
      ])
      return res[0]
    } catch (error) {
      console.log(error);
    }
  }
}
module.exports = new AddressService()